package com.glela.ningchongqing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.glela.common.util.HttpUtil;
import com.glela.common.util.StringUtil;
import com.glela.common.util.XmlUtil;
import com.glela.common.util.YeePayAESUtil;
import com.glela.common.util.YeePayDigest;

public class 易宝支付状态 {
	private final static String SECRET_KEY = "lF0386j067MWZb7817003M8o32iW7918H9Fk3JRV758P10lp182T7B8zte2u";
	private final static String CUSTOMER_NUMBER = "10013842859";
	private final static String ALIPAY_APP_ID = "2016110402547118";
	private final static String ALIPAY_PRIVATE_KEY0 = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALXY9eGtmr7c44i0P9WEB9z7Hml5yFdrGRajJSlR9G/EZ6IhuQWn/mrMYbkPenxuStcqZoZkPkvybBo9SmYEWpI04nnltD5FQmLBMiS6cW1jWcw/Q/cfP7HBqUDRKvZanAq6xtj2Do6HRWcoFsrv7/wFQAVeQpXt1dhN/X9NP8HdAgMBAAECgYEAtD2tyNhH7zIFnPP76WgKWy/UPvtkZbFTlqpyJPiEbVug1ITUXRTcCYM2wTTkVP0E1SvDnyUw0hogqAlj+qYKFf69Lg/ZmlnGu1bLOPqFre2OUyh88pumZ+IwXq32pg9iRgSjibRCLO5QiBxQpryHAFdQ2bZl0aG9gFavMv5X8UkCQQDu+r/wVtKzcMx9l84BWrQ0EGLroKvWgJECJ1rFwDt+2KSAR4Cih4jNAsVSdyyy8GprHqvB26/AK3gh1dXJiiUHAkEAwsyJxYnFgX+oKn8XbnGHwnVyCHuAV/JvDbY3TIpwba6FsJ58Su++/AuzYma0sIKiqFIy37FMIEkIT5gjyj3s+wJABpBMhUVdNCB8/VYWCmN7X5KzpNUc4x9U3EJIc/X7rFg27G8KUWx3jWnuEX3EdIW15otJHGH0Scrn2cYNwSNSMQJBAKXnnc7nr5bDKm5HH6Woe39al2wyAvTkPUDoV+CQZ4CCisoJsMIBvh7buEOuRWWvXOkOWNW7IqK8kJ95a8HrS9ECQQDPzpCA01edsTSbcRHTo9MGqpkYci6Jc/txYCkn4x9IiI8DburMt3EQfxCasnE8XcNbLWupbKSpKmAl70M3Jbeg";
	private final static String ALIPAY_PUBLIC_KEY0 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";

	public static void main(String[] args) {
//		checkYeepayOrderStatus();
		checkAliPayOrderStatus();
//		checkWechatPayOrderStatus();
	}
	

	
	private static String queryWechatPayOrderStatus(String requestid) {
		String status = "FAIL";
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("appid", "wx645f16ce6b3c8894");
			map.put("mch_id", "1408657002"); //商户号
			map.put("out_trade_no", requestid); 
			map.put("nonce_str", "Jj6AOA9a9GY0yhJf4FfROsYHL3exUCMv"); 
			//获得签名
			StringBuilder sign = new StringBuilder();
			sign.append(createSign(map)).append("&key=").append("Jj6AOA9a9GY0yhJf4FfROsYHL3exUCMv");
			String signstr = md5(sign.toString()).toUpperCase();

			String xml = createXML(map, signstr);
			String url = "https://api.mch.weixin.qq.com/pay/orderquery";
			String contentType = "text/xml";
			//		LOGGER.warn("微信支付{}-{}请求参数 ：{}", orderObjectOrderSn, payNo, xml);
			String outxml = doPost(xml, url, contentType);
			//		LOGGER.warn("微信支付{}-{}返回结果 ：{}", orderObjectOrderSn, payNo, outxml);
			//		LOGGER.warn("微信支付{}-{}返回结果 ：{}", orderObjectOrderSn, payNo, JSON.toJSONString(outmap));
			if (outxml != null) {
				Map<String, Object> outmap = xmlStr2Map(outxml);
				if (outmap != null && "SUCCESS".equals(outmap.get("return_code").toString().toUpperCase())) {
					// SUCCESS—支付成功;REFUND—转入退款;NOTPAY—未支付;CLOSED—已关闭;REVOKED—已撤销（刷卡支付）;USERPAYING--用户支付中;PAYERROR--支付失败(其他原因，如银行返回失败)
					if (outmap.get("trade_state") != null) {
						status = outmap.get("trade_state").toString().toUpperCase();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status;
	}
	
	 public static Map<String,Object> xmlStr2Map(String xmlStr){  
	        Map<String,Object> map = new HashMap<String,Object>();  
	        Document doc;  
	        try {  
	            doc = DocumentHelper.parseText(xmlStr);  
	            Element root = doc.getRootElement();    
	            List children = root.elements();    
	            if(children != null && children.size() > 0) {    
	                for(int i = 0; i < children.size(); i++) {    
	                    Element child = (Element)children.get(i);    
	                    map.put(child.getName(), child.getTextTrim());    
	                }    
	            }    
	        } catch (DocumentException e) {  
	            e.printStackTrace();  
	        }  
	        return map;  
	    }  
	
	public static String doPost(String content,String url,String contentType) throws IOException {
		StringBuilder result = new StringBuilder();
        URL postUrl = new URL(url);  
        URLConnection con = postUrl.openConnection(); 
        con.setConnectTimeout(5000);
        con.setDoOutput(true);  
        con.setRequestProperty("Pragma", "no-cache");  
        con.setRequestProperty("Cache-Control", "no-cache"); 
        if(contentType!=null)
        {
        	con.setRequestProperty("Content-Type", contentType);  
        }
        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());    
        out.write(new String(content.getBytes("UTF-8")));  
        out.flush();  
        out.close();  
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));  
        String line = "";  
        for (line = br.readLine(); line != null; line = br.readLine()) {  
        	result = result.append(line);
        }  
		return result.toString();
	}
	
	public static String md5(String source) {
		StringBuffer sb = new StringBuffer(32);
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] array = md.digest(source.getBytes("utf-8"));

			for (int i = 0; i < array.length; i++) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
			}
		} catch (Exception e) {
			return null;
		}
		return sb.toString();
	}
	public static String createSign(Map<String, String> params) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        //微信要求 参数名ASCII字典序排序
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        boolean first = true;
        for (Object key : keys) {
            if (first) {
                first = false;
            } else {
                temp.append("&");
            }
            temp.append(key).append("=");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = value.toString();
            }
            temp.append(valueString);
            //temp.append(URLEncoder.encode(valueString, "UTF-8"));
        }
        return temp.toString();
    }
	
	public static String createXML(Map<String, String> params, String sign) throws UnsupportedEncodingException {
        Set<String> keysSet = params.keySet();
        //微信要求 参数名ASCII字典序排序
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuffer temp = new StringBuffer();
        temp.append("<xml>") ;
        for (Object key : keys) {
            temp.append("<").append(key).append(">");
            Object value = params.get(key);
            String valueString = "";
            if (null != value) {
                valueString = value.toString();
            }
            temp.append(valueString);
            temp.append("</").append(key).append(">");
        }
        
        temp.append("<sign>").append(sign).append("</sign>").append("</xml>") ;
        return temp.toString();
    }

	public static void checkYeepayOrderStatus(){
		String payOrders = "PAY151269899629543085;PAY151269922373829893;PAY151270010499966984;PAY151270024210333031;PAY151270038440924219;PAY151270038873288688;PAY151270046579732878;PAY151270047597351471;PAY151270052452899352;PAY151270053112627914;PAY151270053449331811;PAY151270049216467547;PAY151270448694034441;PAY151270541527507812;PAY151270859375446374;PAY151270983999732170";
		for (String orderPay : payOrders.split(";")) {
			System.out.println(orderPay + "-------->" + queryYeePayOrderStatus(orderPay));;
		}
	}
	
	public static void checkAliPayOrderStatus(){
		String requestids = "PAY151417231325666960;"+
				"PAY151417302186030642;"+
				"PAY151417306856690532;"+
				"PAY151417358435899104;"+
				"PAY151417363414688407;"+
				"PAY151417373295651210;"+
				"PAY151417381363344513;"+
				"PAY151417383390723220;"+
				"PAY151417390183298915;"+
				"PAY151417390458482121;"+
				"PAY151417398997610321;"+
				"PAY151417399286763225;"+
				"PAY151417403937215821;"+
				"PAY151417403954939011;"+
				"PAY151417405848757016;"+
				"PAY151417408561335129;"+
				"PAY151417412578502923;"+
				"PAY151417412857992917;"+
				"PAY151417422365721715;"+
				"PAY151417424061717727;"+
				"PAY151417424233224425;"+
				"PAY151417429997333629;"+
				"PAY151417435185648821;"+
				"PAY151417435290586330;"+
				"PAY151417444739337938;"+
				"PAY151417445224557124;"+
				"PAY151417446141395127;"+
				"PAY151417455675094038;"+
				"PAY151417458586842627;"+
				"PAY151417458814336928;"+
				"PAY151417461215849333;"+
				"PAY151417462405682432;"+
				"PAY151417462418201245;"+
				"PAY151417463494542339;"+
				"PAY151417463540291939;"+
				"PAY151417463708576440;"+
				"PAY151417464692845445;"+
				"PAY151417464787338651;"+
				"PAY151417465910016043;"+
				"PAY151417465984371654;"+
				"PAY151417466089303341;"+
				"PAY151417466106734755;"+
				"PAY151417466395830852;"+
				"PAY151417466603505448;"+
				"PAY151417466867158949;"+
				"PAY151417468339342162;"+
				"PAY151417469275500244;"+
				"PAY151417470153229161;"+
				"PAY151417473103731675;"+
				"PAY151417473445052663;"+
				"PAY151417474713709666;"+
				"PAY151417474753525270;"+
				"PAY151417475992596878;"+
				"PAY151417476901326881;"+
				"PAY151417476919876582;"+
				"PAY151417479374929377;"+
				"PAY151417479607340778;"+
				"PAY151417479637754479;"+
				"PAY151417482038077283;"+
				"PAY151417482498070890;"+
				"PAY151417482790947002;"+
				"PAY151417484695759890;"+
				"PAY151417486148277884;"+
				"PAY151417486165866095;"+
				"PAY151417490408140994;"+
				"PAY151417492658495118;"+
				"PAY151417493415531399;"+
				"PAY151417495089714176;"+
				"PAY151417496883063589;"+
				"PAY151417496926694390;"+
				"PAY151417499655354397;"+
				"PAY151417500372183891;"+
				"PAY151417500936301892;"+
				"PAY151417501148874002;"+
				"PAY151417504521052693;"+
				"PAY151417507608337284;"+
				"PAY151417512526053196;"+
				"PAY151417519485992624;"+
				"PAY151417519669473143;"+
				"PAY151417520904734144;"+
				"PAY151417522042630047;"+
				"PAY151417522450174622;"+
				"PAY151417523560008626;"+
				"PAY151417528558821405;"+
				"PAY151417529770161406;"+
				"PAY151417534152738701;"+
				"PAY151417535415934302;"+
				"PAY151417539012662004;"+
				"PAY151417542017874625;"+
				"PAY151417544213150659;"+
				"PAY151417546268285160;"+
				"PAY151417549041744025;"+
				"PAY151417549782720228;"+
				"PAY151417550316781865;"+
				"PAY151417552120556232;"+
				"PAY151417552587703631;"+
				"PAY151417555311670433;"+
				"PAY151417555606597534;"+
				"PAY151417556681092742;"+
				"PAY151417559987817736;"+
				"PAY151417560606816435;"+
				"PAY151417560825101272;"+
				"PAY151417565698146286;"+
				"PAY151417566056022755;"+
				"PAY151417567875670293;"+
				"PAY151417568809815431;"+
				"PAY151417569359175233;"+
				"PAY151417572261754910;"+
				"PAY151417573938575541;"+
				"PAY151417574565780754;"+
				"PAY151417576991541215;"+
				"PAY151417577696442871;"+
				"PAY151417578317801056;"+
				"PAY151417579253340963;"+
				"PAY151417579821617149;"+
				"PAY151417579907402862;"+
				"PAY151417580858264653;"+
				"PAY151417584056693560;"+
				"PAY151417584645535966;"+
				"PAY151417585805294629;"+
				"PAY151417585988876468;"+
				"PAY151417586605029233;"+
				"PAY151417586769018178;"+
				"PAY151417589629615385;"+
				"PAY151417590246938280;"+
				"PAY151417590830244183;"+
				"PAY151417591716757675;"+
				"PAY151417596273704678;"+
				"PAY151417596556962676;"+
				"PAY151417597636158252;"+
				"PAY151417599429211793;"+
				"PAY151417606779395659;"+
				"PAY151417607009782998;"+
				"PAY151417608138073796;"+
				"PAY151417610986862702;"+
				"PAY151417612556358001;"+
				"PAY151417614003526807;"+
				"PAY151417614104348707;"+
				"PAY151417615325840708;"+
				"PAY151417618106788113;"+
				"PAY151417624874418920;"+
				"PAY151417633249142228;"+
				"PAY151417640031696029;"+
				"PAY151417640924230735;"+
				"PAY151417650628130939;"+
				"PAY151417660623554449;"+
				"PAY151417663246782408;"+
				"PAY151417668657852507;"+
				"PAY151417717476673610;"+
				"PAY151417722773327761;";
		String[] arr = requestids.split(";");
		for (int i=0;i<arr.length;i++) {
			System.out.println(arr[i] + "---->" + queryAliPayOrderStatus(arr[i]));
		}
	}
	
	public static String queryYeePayOrderStatus(String requestid) {
		String status = "FAIL";
		try {
			String keyForAes = SECRET_KEY.substring(0, 16);// 密文
			String customernumber = CUSTOMER_NUMBER;// 商户编号
			String[] stringArray = { customernumber, requestid};
			// 签名完成
			String hmac = YeePayDigest.getHmac(stringArray, SECRET_KEY);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("customernumber", customernumber);// 商户编号
			paramMap.put("requestid", requestid);//商户订单号
			paramMap.put("hmac", hmac);//商户订单号
			String url = "https://o2o.yeepay.com/zgt-api/api/queryOrder";
			String data = YeePayAESUtil.encrypt(JSONObject.toJSONString(paramMap), keyForAes);
			String content = "customernumber=" + customernumber + "&data=" + data;
			String result = YeePayAESUtil.decrypt(JSONObject.parseObject(HttpUtil.doPost(content, url, "application/x-www-form-urlencoded")).get("data").toString(), keyForAes);
			// INIT：未支付，SUCCESS：已支付，FAIL：支付失败，SETTLECONFIRM：担保交易确认，仅担保交易时存在该状态
			if(!StringUtil.isEmpty(JSONObject.parseObject(result).getString("status"))){
				status = JSONObject.parseObject(result).getString("status");
			}
		} catch (Exception e) {
			status ="ERROR";
		}
		return status;
	}
	
	public static String queryAliPayOrderStatus(String requestid) {
		String status = "FAIL";
		try {
			AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", ALIPAY_APP_ID, ALIPAY_PRIVATE_KEY0,"json","GBK", ALIPAY_PUBLIC_KEY0);
			AlipayTradeQueryModel model = new AlipayTradeQueryModel();
			model.setOutTradeNo(requestid);
			AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
			request.setBizModel(model);
			AlipayTradeQueryResponse response = alipayClient.execute(request);
			// 交易状态： WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
			if (response != null && response.getTradeStatus() != null) {
				status = response.getTradeStatus();
			}
		} catch (Exception e) {
			
		}
		return status;
	}
	
}
